<?php

namespace Admin\Controller;

use Think\Controller;
use Think\Verify;

class LoginController extends Controller {

    public function index() {
        if (IS_POST) {
            $username = I('username', '', 'addslashes,trim');
            $password = I('password');
            $verify = I('verify');
            if (!$username) {
                exit(json_encode([
                    'status' => 'error',
                    'message' => '登录名不能为空',
                ]));
            }
            if (!$password) {
                exit(json_encode([
                    'status' => 'error',
                    'message' => '登陆密码不能为空',
                ]));
            }
            if (!$verify) {
                exit(json_encode([
                    'status' => 'error',
                    'message' => '验证码不能为空',
                ]));
            }

            $Captcha = new CaptchaController();
            if (!$Captcha->check($verify)) {
                exit(json_encode([
                    'status' => 'error',
                    'code' => '99',
                    'message' => '验证码不正确',
                ]));
            }

            $result = M('Manager')->where(['username' => $username])->find();
            if (!$result) {
                exit(json_encode([
                    'status' => 'error',
                    'code' => '99',
                    'message' => '用户不存在',
                ]));
            }
            $password = entrypt_password($password);
            if ($result['password'] != $password) {
                exit(json_encode([
                    'status' => 'error',
                    'code' => '99',
                    'message' => '登陆密码不正确',
                ]));
            }

            //认证字符串
            $token = md5($result['id'] . time() . uniqid());

            M('Manager')->where(['id' => $result['id']])->save([
                'login_time' => time(),
                'login_ip' => get_client_ip(),
                'login_count' => ['exp', 'login_count+1'],
                'token' => $token
            ]);

            $auth = $token;
            cookie('_auth', authcode($auth, 'ENCODE'));
            exit(json_encode([
                'status' => 'success'
            ]));
        } else {

            $auth = cookie('_auth');
            list($id, $password) = explode('\t', authcode($auth));
            $user_info = M('Manager')->find($id);
            if ($user_info && $user_info['password'] == $password) {
                redirect(U('index/index'));
            }
            $this->display();
        }
    }

    public function logout() {
        cookie('_auth', null);
        redirect(U('login/index'));
    }

}
